package main

import (
	"chat_project/control"
	"html/template"
	"log"
	"net/http"
)

// 多个路由绑定一个回调函数,动态渲染模板
func BindAllRequest() {
	// 指定所有解析模板, *表示为文件 **表示为文件夹
	tpl, err := template.ParseGlob("view/**/*")
	if err != nil {
		// 表示模板渲染失败后直接退出
		log.Fatal(err.Error())
	}
	// 循环所有文件,动态渲染
	for _, v := range tpl.Templates() {
		tplnname := v.Name()
		http.HandleFunc(tplnname, func(writer http.ResponseWriter, request *http.Request) {
			tpl.ExecuteTemplate(writer, tplnname, nil)
		})
	}
}

var userControl control.UserControl
var contactControl control.ContactControl
var chatControl control.ChatControl
var attachControl control.AttachControl

func main() {
	// 提供指定目录的静态访问权限,否则上面开启/后,指定静态资源只能访问/asset/下
	http.Handle("/asset/", http.FileServer(http.Dir(".")))
	// 指定mnt为图片静态资源路径
	http.Handle("/mnt/", http.FileServer(http.Dir(("."))))
	// 动态渲染多个模板文件
	BindAllRequest()
	// 测试注册函数
	http.HandleFunc("/user/register", userControl.UserRegister)
	http.HandleFunc("/user/login", userControl.UserLogin)
	http.HandleFunc("/contact/addfriend", contactControl.AddFriend)
	http.HandleFunc("/contact/loadfriend", contactControl.SearchFriend)
	http.HandleFunc("/chat", chatControl.Chat)
	http.HandleFunc("/attach/upload", attachControl.Upload)
	http.ListenAndServe(":8080", nil)
}
